<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2020/5/14
 * Time: 9:41
 */

namespace app\service;


use Exception;
use OSS\OssClient;

class AliyunOss extends BaseService
{
    public $accessKeyId = 'LTAI4FtKEfbCr1BQzEuDX1T2';
    public $accessKeySecret = 'z9rEkBsLNVd1uj2cO3tad0RDSeAde2';
    public $param = [];
    /*public $oss_dir = [
        '1' => 'image/',
        '2' => 'uploads/',
        '3' => 'upload/',
    ];*/

    /**
     *
     */
    public function __construct()
    {
        $dir_name = APP_PATH . '../oss';
        if (is_file($dir_name . '/autoload.php')) {
            require_once($dir_name . '/autoload.php');
        }
    }

    /**
     * @name 设置参数
     * @author zay
     * @date 2019/5/31 11:11
     * @param $data
     * @throws Exception
     * @return $this
     */

    public function setParam($data)
    {
        $this->param = $data;
        if (empty($this->param['file_dir']) || empty($this->param['file_name'])) {
            throw new Exception('缺少必要的参数');
        }
        return $this;
    }

    /**
     * @name 文件上传或图片上传
     * @author zay
     * @date 2019/5/27 14:16
     * @return array
     * @throws Exception
     */

    public function upload()
    {
        try{
            // 阿里云主账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM账号进行API访问或日常运维，请登录 https://ram.console.aliyun.com 创建RAM账号。
            $accessKeyId = $this->accessKeyId;
            $accessKeySecret = $this->accessKeySecret;
            //Endpoint以杭州为例，其它Region请按实际情况填写。
            $endpoint = "http://oss-cn-hangzhou.aliyuncs.com";
            $bucket = 'idc-image';
            $oss_dir = $this->param['file_dir'];
            if (empty($_FILES['file'])) {
                throw new Exception('文件不存在');
            }
            $file = $_FILES['file'];
            $name = $file['name'];
            $format = strrchr($name, '.');
            $fileName = $this->param['file_name'].$format;
            /*判断图片格式*/
            $allow_type = ['.jpg', '.jpeg', '.gif', '.png'];
            if (!in_array($format, $allow_type)) {
                throw new Exception('文件格式不正确');
            }
            $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);
            //执行阿里云上传
            $result = $ossClient->uploadFile($bucket, $oss_dir . '/' . $fileName, $file['tmp_name']);
            if (!isset($result['info']['url'])) {
                throw new Exception('上传失败');
            }
            $url = $result['info']['url'];
            $param = parse_url($url);
            $data = [
                'zt' => 1,
                'sql_path' => ltrim($param['path'],'/'),
                'domain_name' => config('OSS_PREFIX'),
            ];
        }catch (Exception $e){
            $data = [
                'zt' => 0,
                'error'=>$e->getMessage()
            ];
        }
        return $data;

    }

    /**
     * @name 图片上传
     * @author zay
     * @date 2019/5/27 14:16
     * @return array
     * @throws Exception
     */

    public function imageUpload()
    {
        // 阿里云主账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM账号进行API访问或日常运维，请登录 https://ram.console.aliyun.com 创建RAM账号。
        $accessKeyId = $this->accessKeyId;
        $accessKeySecret = $this->accessKeySecret;
        //Endpoint以杭州为例，其它Region请按实际情况填写。
        $endpoint = "http://oss-cn-hangzhou.aliyuncs.com";
        $bucket = 'juzishiwan';
        $oss_dir = 'admin/images/';
        if (empty($_FILES['file'])) {
            throw new Exception('文件不存在');
        }
        $file = $_FILES['file'];
        $name = $file['name'];
        $format = strrchr($name, '.');//截取文件后缀名如 (.jpg)
        /*判断图片格式*/
        $allow_type = ['.jpg', '.jpeg', '.gif', '.png'];
        if (!in_array($format, $allow_type)) {
            throw new Exception('文件格式不正确');
        }
        $fileName = md5(date('YmdHis', time()) . uniqid());
        $fileName = $fileName . $format;
        $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);
        //执行阿里云上传
        $result = $ossClient->uploadFile($bucket, $oss_dir . $fileName, $file['tmp_name']);
        if (!isset($result['info']['url'])) {
            throw new Exception('上传失败');
        }
        $url = $result['info']['url'];
        $param = parse_url($url);
        $data = [
            'url' => $param['path'],
        ];
        return $data;
    }
}